﻿/**
 * SlotDuino
 * 
 * Copyright (c) 2011/2012 Thiago Hummel Moreira, Ricardo Mizuuti, Rafael Mufato, Bruno Sakai, Andre Turina
 * 
 * Permission is hereby granted, free of charge, to any person
 * obtaining a copy of this software and associated documentation
 * files (the "Software"), to deal in the Software without
 * restriction, including without limitation the rights to use,
 * copy, modify, merge, publish, distribute, sublicense, and/or
 * sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
 * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
 * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
 * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */
using System;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Net;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using SlotDuino.Sockets;
using SlotDuino.Util;

namespace SlotDuino.UI.Pages
{
    /// <summary>
    /// Interaction logic for TrackSelect.xaml
    /// </summary>
    public partial class TrackSelect : Page
    {
        private DatagramListener _listener;
        private ObservableCollection<NetTrack> _trackList;
        private CollectionViewSource _viewSource;
        private Window _mainWindow;
        private CancelEventHandler _mainWindowClosingHandler;
        private SlotDaemonClient _client;
        private ConnectionStatusChangedEventHandler _clientConnectionStatusHandler;

        public TrackSelect()
        {
            InitializeComponent();
        }

        private void Page_Loaded(object sender, RoutedEventArgs e)
        {
            //Initialize the track list
            _trackList = new ObservableCollection<NetTrack>();

            //Attach the track list to the associated view source
            _viewSource = ((CollectionViewSource)(FindResource("serversSource")));
            _viewSource.Source = _trackList;

            //Start the UDP listener
            _listener = new DatagramListener();
            _listener.DatagramReceived += new DatagramReceivedEventHandler(OnDatagramReceived);
            _listener.Start();

            //Get a reference to the mainWindow
            _mainWindow = Window.GetWindow(this);
            //Keep a reference to the handler, will be needed to detach it later
            _mainWindowClosingHandler = new CancelEventHandler(mainWindow_Closing);
            //Attach a handler to window_closing event (ensure the listener will be stoped)
            _mainWindow.Closing += _mainWindowClosingHandler;

            //Get a reference to the application SloDaemon client
            _client = ((App)Application.Current).Client;
            //Keep a referente to the handler, will be needed to detach it later
            _clientConnectionStatusHandler = new ConnectionStatusChangedEventHandler(OnConnectionStatusChanged);
            //Listen to connection status change
            _client.ConnectionStatusChanged += _clientConnectionStatusHandler;

            dataGrid.SelectedItem = null;
                        
            //Broadcast for tracks
            GetAvaliableTracks();
        }

        void OnConnectionStatusChanged(TcpClient sender, ConnectionStatusChangedEventArgs e)
        {
            switch (e.Status)
            {
                //The connection process started
                case TcpClient.ConnectionStatus.Connecting:
                    Dispatcher.Invoke(new Action(() => { IsEnabled = false; }));
                    break;
                //The connection was sussefuly made
                case TcpClient.ConnectionStatus.Connected:
                    var application = ((App)Application.Current);
                    //@TODO: Discover if we alredy know this track and set it as the current track
                    application.Properties["currentTrackId"] = 1;

                    Dispatcher.Invoke(new Action(() => {
                        //Go back to dashboard
                        NavigationService.GoBack();
                    }));
                    break;
                //There was an error connecting to server
                case TcpClient.ConnectionStatus.Error:
                    Msg.ShowError(_client.TcpClient.LastError);
                    Dispatcher.Invoke(new Action(() => { IsEnabled = true; }));
                    break;
            }
        }

        private void OnExit()
        {
            _listener.Stop();
        }

        void mainWindow_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            OnExit();
        }

        private void Page_Unloaded(object sender, RoutedEventArgs e)
        {
            //Remove the window closing event handler
            _mainWindow.Closing -= _mainWindowClosingHandler;
            //Remove the client connection status changed handler
            _client.ConnectionStatusChanged -= _clientConnectionStatusHandler;

            OnExit();
        }

        void OnDatagramReceived(object sender, DatagramReceivedEventArgs e)
        {
            NetTrack track = new NetTrack();
            track.Name = Encoding.UTF8.GetString(e.Data);
            track.Address = e.RemoteHost.Address;

            if (!_trackList.Contains(track))
            {
                Dispatcher.Invoke(new Action(() => {
                    _trackList.Add(track);

                    if (null == dataGrid.SelectedItem)
                        dataGrid.SelectedIndex = 0;
                }));
            }
#if DEBUG
            else
            {
                Console.WriteLine("Already knowed: " + track.Address);
            }
#endif
        }
        
        private void btnRefresh_Click(object sender, RoutedEventArgs e)
        {
            //Broadcast for tracks
            GetAvaliableTracks();
        }

        private void btnHost_Click(object sender, RoutedEventArgs e)
        {
            SpecificTrack specificTrack = new SpecificTrack();
            specificTrack.Owner = Application.Current.MainWindow;
            if (true == specificTrack.ShowDialog() && null != specificTrack.Address)
            {
                IPAddress ip = IPAddress.Parse(specificTrack.Address);
                ConnectToTrack(ip);
            }
        }

        private void GetAvaliableTracks()
        {
            Network.BroadcastMsg("HELLO", 1234);
        }

        private void ConnectToTrack(IPAddress address)
        {
            var client = ((App)Application.Current).Client;
            client.Connect(address);
        }

        private void btnConnect_Click(object sender, RoutedEventArgs e)
        {
            NetTrack track = (NetTrack)dataGrid.SelectedItem;
            if (null != track)
                ConnectToTrack(track.Address);
        }
    }

    public class NetTrack 
    {
        public string Name { get; set; }
        public IPAddress Address { get; set; }

        public override bool Equals(object obj)
        {
            return this.GetHashCode() == obj.GetHashCode();
        }

        public override int GetHashCode()
        {
            return Address.GetHashCode();
        }
    }
}
